package com.clothing.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.clothing.dao.WxAppDao;
import com.clothing.entity.WxApp;
import com.clothing.service.WxAppService;
import com.clothing.utils.Utils;
import com.clothing.utils.WeixinUtils;
import com.clothing.utils.weixin.KeynoteItem;
import com.clothing.utils.weixin.TemplateMsg;
import com.clothing.utils.weixin.TemplateMsg.WeixinTemplate;

/**
 * @ClassName: WxAppServiceImpl 
 * @Description: TODO(Service) 
 * @author Charles.Tao 
 * @date 2017年9月11日 上午10:27:16 
 * @version 1.0
 */
@Service
public class WxAppServiceImpl extends BaseServiceImpl<WxApp, Long> implements
        WxAppService
{
    private static Logger logger = Logger.getLogger(WxAppServiceImpl.class);
    
    @Autowired
    private WxAppDao wxAppDao;

    public WxApp getAccessToken(WxApp app, Boolean refresh)
    {
        if (app == null)
        {
            return null;
        }
        
        long currentTimeMillis = System.currentTimeMillis();
        
        if (app.getAccessToken() == null
            || app.getTokenExpiresin() == null
            || (currentTimeMillis > app.getTokenExpiresin().longValue()) 
            || Utils.isTrue(refresh))
        {
            JSONObject jo = WeixinUtils.fetchAccessToken(app.getAppId(), app.getAppSecret());
            
            if (jo != null)
            {
                try
                {
                    app.setAccessToken(jo.getString("access_token"));
                    app.setTokenExpiresin(Long.valueOf(System.currentTimeMillis() + 1000 * (jo.getIntValue("expires_in") - 300)));
                    wxAppDao.merge(app);
                }
                catch(JSONException e)
                {
                    logger.error("getAccessToken() JSONException="  + e.toString());
                    return null;
                }
            }
        }
        
        return app;
    }
    
    @Override
    public boolean sendTemplateMsg(String openId, String url, KeynoteItem first, KeynoteItem remark, List<KeynoteItem> keynotes, WeixinTemplate weixinTemplate)
    {
        WxApp wxApp = wxAppDao.find(1L);

        if (null == wxApp)
        {
            return false;
        }

        TemplateMsg msg = new TemplateMsg();
        msg.setTouser(openId);
        msg.setUrl(url);
        msg.setTemplate_id(weixinTemplate.getCodeName());
        msg.setData(first, remark, keynotes);
        JSONObject resultObj = WeixinUtils.sendTemplateMsg(getAccessToken(wxApp, false).getAccessToken(), msg.toJson());
        String isOk = resultObj.getString("errmsg");
        
        if (!"ok".equals(isOk))
        {
            return false;
        }
        
        return true;
    }
}